package com.yugao.fintech.draper.admin.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yugao.fintech.draper.admin.entity.SysPost;
import com.yugao.fintech.draper.admin.mapper.PostMapper;
import com.yugao.fintech.draper.admin.service.PostService;
import com.yugao.fintech.draper.admin.convert.PostConvert;
import com.yugao.fintech.draper.admin.param.PostDTO;
import com.yugao.fintech.draper.admin.param.PostQuery;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Slf4j
@Service
public class PostServiceImpl implements PostService {
    @Autowired
    private PostMapper postMapper;

    @Override
    public Page<PostDTO> pageQuery(PostQuery postQuery) {
        LambdaQueryWrapper<SysPost> wrapper = Wrappers.<SysPost>lambdaQuery()
                .like(StrUtil.isNotBlank(postQuery.getPostCode()), SysPost::getPostCode, postQuery.getPostCode())
                .like(StrUtil.isNotBlank(postQuery.getPostName()), SysPost::getPostName, postQuery.getPostName());
        Page<SysPost> postList = postMapper.selectPage(Page.of(postQuery.getPageNum(), postQuery.getPageSize()), wrapper);
        return PostConvert.INSTANCE.convert(postList);
    }

    @Override
    public Boolean addPost(PostDTO postDTO) {
        SysPost sysPost = PostConvert.INSTANCE.convert(postDTO);
        return postMapper.insert(sysPost) > 0;
    }

    @Override
    public Boolean updatePost(PostDTO postDTO) {
        SysPost sysPost = PostConvert.INSTANCE.convert(postDTO);
        return postMapper.updateById(sysPost) > 0;
    }

    @Override
    public PostDTO findById(Long id) {
        SysPost sysPost = postMapper.selectById(id);
        return PostConvert.INSTANCE.convert(sysPost);
    }

    @Override
    public List<PostDTO> findAll() {
        List<SysPost> postList = postMapper.selectList(Wrappers.emptyWrapper());
        return PostConvert.INSTANCE.convert(postList);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean deletePost(Long id) {
        return postMapper.deleteById(id) > 0;
    }
}